const parser = require('../parser')

module.exports = class Queue {
  constructor(torrent) {
    this._torrent = torrent
    this._queue = []
    this._originQueue = []
    this._choked = true
  }

  resetQueue () {
    this._queue = this._originQueue
  }

  enqueue (pieceIndex) {
    const blockNum = parser.blockNum(this._torrent, pieceIndex)
    for (let i = 0; i < blockNum; i++) {
      this._queue.push({
        index: pieceIndex,
        begin: i * parser.BLOCK_LEN,
        length: parser.blockLen(this._torrent, pieceIndex, i)
      })
    }

    this._originQueue = this._queue
  }

  unqueue () {
    const block = this._queue.shift()
    if (!this.len()) {
      this.resetQueue()
    }
    return block
  }

  unchoke () {
    this._choked = false
  }

  isChoked () {
    return this._choked
  }

  len () {
    return this._queue.length
  }
}